<template>
  <div class="md:flex">
    <Input class="w-1/2 mr-2" v-model:value="code" placeholder="验证码" />
    <Select class="w-1/3" v-if="props.selectOptions" v-model:value="option">
      <SelectOption v-for="option in props.selectOptions" v-bind:key="option.value" :value="option.value"
        >{{ option.label }}
      </SelectOption>
    </Select>
    <Button type="primary" class="w-1/3 ml-2" v-bind="props.buttonOthers" @click="sendHandler" :disabled="disable">
      <slot>{{ buttonName }}</slot>
    </Button>
  </div>
</template>

<script lang="ts" setup>
import { Select, SelectOption, Button, Input } from 'ant-design-vue';
import { nextTick, ref, watch } from 'vue';
import { useMessage } from '/@/hooks/web/useMessage';

const buttonName = ref('获取');
const disable = ref(false);
const time = ref(5);
const code = ref();
const option = ref();
const emits = defineEmits(['code']);
let count;
const { createMessage } = useMessage();
const props = defineProps({
  selectOptions: Array,
  limitTimer: Number,
  buttonFunction: Function,
  buttonName: String,
  buttonOthers: Object,
});

nextTick(() => {
  option.value = props.selectOptions[0].value;
});
const sendHandler = async () => {
  disable.value = await true;
  if (props.buttonFunction) {
    await props.buttonFunction(option.value);
  }
  count = setInterval(() => {
    --time.value;
  }, 1000);
};

const getVerificationCode = () => {
  if (code.value) {
    return code.value;
  } else {
    createMessage.error('请填写验证码');
    throw new Error('请填写验证码');
  }
};

const clearCode = () => {
  code.value = undefined;
};

const getVerficationType = () => {
  return option.value;
};

watch(
  () => props.limitTimer,
  () => {
    if (props.limitTimer) {
      time.value = props.limitTimer;
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
watch(
  () => time.value,
  async () => {
    if (disable.value) {
      if (time.value > 0) {
        buttonName.value = time.value + '秒';
      } else {
        clearInterval(count);
        disable.value = await false;
        time.value = props.limitTimer === undefined ? 5 : props.limitTimer;
        buttonName.value = await (props.buttonName === undefined ? '发送验证码' : props.buttonName);
      }
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

watch(
  () => props.buttonName,
  () => {
    if (props.buttonName) {
      buttonName.value = props.buttonName;
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

watch(
  () => code.value,
  () => {
    emits('code', code.value);
  }
);

defineExpose({ getVerificationCode, getVerficationType, clearCode });
</script>
